package com.example.gate.test;

import com.example.game.CReq;
import com.example.game.LoginRequest;
import com.example.game.StrReq;
import com.example.gate.websocket.WSClientProtobufDecoder;
import com.example.gate.websocket.WSClientProtobufEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;

@Slf4j
public class WebSocketClient {
    private final String url;
    private Channel channel;
    private EventLoopGroup group;
    private WebSocketClientHandler handler;

    public WebSocketClient(String url) {
        this.url = url;
    }

    public void connect() throws Exception {
        group = new NioEventLoopGroup();
        try {
            URI uri = new URI(url);
            String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
            final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
            final int port = uri.getPort() == -1 ? ("ws".equals(scheme) ? 80 : 443) : uri.getPort();

            WebSocketClientHandshaker webSocketClientHandshaker = WebSocketClientHandshakerFactory.newHandshaker(
                    uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders());

            // 创建握手处理器
            handler = new WebSocketClientHandler();
            WebSocketClientHandshakerHandler handshakerHandler = new WebSocketClientHandshakerHandler(webSocketClientHandshaker);

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(
                                    new HttpClientCodec(),
                                    new HttpObjectAggregator(8192),
                                    handshakerHandler,
                                    new WSServerProtobufDecoder(),
                                    new WSServerProtobufEncoder(),
                                    handler)
                            ;
                        }
                    });

            // 连接服务器
            ChannelFuture future = bootstrap.connect(host, port).sync();
            channel = future.channel();
            handshakerHandler.handshakeFuture().sync();
        } catch (Exception e) {
            group.shutdownGracefully();
            throw e;
        }
    }

    public void send(String message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(new TextWebSocketFrame(message));
        }
    }

    public void send() {

        LoginRequest login = LoginRequest.newBuilder().setUserId("1321").setToken("token").build();

        // 创建测试请求
        CReq request = CReq.newBuilder()
                .setId(1)
                .setCode(2001) // 测试协议号
                .setBody(com.google.protobuf.ByteString.copyFrom(login.toByteArray()))
                .build();
        log.info("发送WebSocket请求: id={}, code={}", request.getId(), request.getCode());

        // 将CReq转换为字节数组
        //byte[] data = request.toByteArray();

        // 创建ByteBuf
        //ByteBuf buffer = Unpooled.wrappedBuffer(data);

        // 创建BinaryWebSocketFrame
        //BinaryWebSocketFrame frame = new BinaryWebSocketFrame(buffer);

        // 发送消息
        channel.writeAndFlush(request);
    }

    public void send1() {

        String info = "lHxpfRr%2Bn5WjmvJTDnfeDeso6E9DsqhgDzTDQcR50CCGJHwvvOXUaUXoz%2FkGFuo%2BY3ayIqr9faLi5lCgUiJKjjo2H2wrVe2jGtmU%2B%2FmWZyfhPusHS1IldCodHxIolMjpXniLYe%2FijizuGsTv1AomQfgCM1pzYoyJzjgha1ni5g0B0T5FGVRQLk5N6I%2Bok5GKHOCsP9XLFuO4bO3%2FiUeOr95tw8DFpHNPs4eKYx4EF2hbNSnqbjhHkUKfrDA%2BZjht1U1CVOM2NCHnRsOI09fl3rD9UCwp7T7YjRZR39YdHRWc27fER4vcTL0mbI0xo9%2F%2B73ErsjOT4rbdz%2BqviPwPWqaLSGi0FnFK%2FcpU9lGthnlxvJj%2BbawlNrF2WfwZZbw9TNI2kBKk2crOoFyXFUCmg5JZJscy0sXLqgIQIWtTzRGEW0ye%2FcG2DwIMWDiSBY%2FlAOMso8FkfawJMl2ioC3rAtJhmlqj92itcSfozGg%2B9BXePmFT4hpWwdc4IWTGJeOsFJonqREB9brq7NFgE%2B24tCvg%2BmOv1zyJYGYaSZbJ2vcBs%2BHQ2imyFgvnqwRT0cnEa%2BOLEG2NfDIwRz8AgxyQK%2BOWtk77H8McgoqXT4zQFEbZYQzccr63%2BbuLobERUKcib14isCMZT9Ppf%2FeppKktJgGWoKTsb5MHvCM0evx%2FfkNmXyN5hru1EUZrVbxZouoNGADgsLXtL3411JM0qewRuEEca%2B1%2BO3KoNYnXOPXkdgdg4uUq3pDXF4i7qpe25fPH4a3Z5H1BQR2I9VvFkaL4MlZArIPytZzCmWGZD5h7G%2B8%2FAe9DROfHOfFaTIMZDfx7%2BzV7tIuN2t8dPPUUhKLd56nTto%2Fm9EDsKmvFL6TKpm0Yv3naUBqlsL2q1oamGhCMWhFBaDZciOyYV%2BaMEgBYfg%3D%3D";

        StrReq build = StrReq.newBuilder().setStr(info).build();

        // 创建测试请求
        CReq request = CReq.newBuilder()
                .setId(1)
                .setCode(201001) // 测试协议号
                .setBody(com.google.protobuf.ByteString.copyFrom(build.toByteArray()))
                .build();
        log.info("发送WebSocket请求: id={}, code={}", request.getId(), request.getCode());

    }

    public void close() {
        if (channel != null) {
            channel.writeAndFlush(new CloseWebSocketFrame());
            channel.closeFuture().syncUninterruptibly();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}